<template>
  <div class="divBox relative">
    <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: 0 }">
      <div class="padding-add">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="配送员名称" prop="deliveryPersonnelName">
            <el-input
              v-model="queryParams.deliveryPersonnelName"
              placeholder="请输入配送员名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="deliveryPersonnelPhone">
            <el-input
              v-model="queryParams.deliveryPersonnelPhone"
              placeholder="请输入手机号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="车牌号" prop="licensePlateNumber">
            <el-input
              v-model="queryParams.licensePlateNumber"
              placeholder="请输入车牌号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="box-card mt14" :body-style="{ padding: '20px 20px' }" shadow="never" :bordered="false">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['platform:delivery:personnel:save']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['platform:delivery:personnel:update']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['platform:delivery:personnel:delete']"
            >删除</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['platform:delivery:export']"
            >导出</el-button
          >
        </el-col> -->
      </el-row>

      <el-table v-loading="loading" :data="deliveryList" @selection-change="handleSelectionChange">
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="配送员" align="center" prop="deliveryPersonnelName" />
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">
            {{ scope.row.sex === 1 ? '男' : scope.row.sex === 0 ? '女' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="联系电话" align="center" prop="deliveryPersonnelPhone" />
        <el-table-column label="归属门店" align="center" prop="saleRoomName" />
        <el-table-column label="身份证有效期" align="center" prop="validityPeriodOfIdCard" />
        <el-table-column label="车牌号" align="center" prop="licensePlateNumber" />
        <el-table-column label="状态" align="center" prop="isDisable">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isDisable === 1 ? 'success' : 'info'">
              {{ scope.row.isDisable === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.createTime">{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注说明" align="center" prop="remarks" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['platform:delivery:personnel:update']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['platform:delivery:personnel:delete']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="860px" append-to-body class="rider-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="rider-form">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="配送员名称" prop="deliveryPersonnelName">
              <el-input v-model="form.deliveryPersonnelName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="deliveryPersonnelPhone">
              <el-input v-model="form.deliveryPersonnelPhone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-if="!form.id">
              <el-input v-model="form.password" type="password" show-password placeholder="请输入密码" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属门店" prop="saleRoomId">
              <el-select v-model="form.saleRoomId" placeholder="请选择">
                <el-option v-for="item in saleRoomList" :key="item.id" :label="item.roomName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="licensePlateNumber">
              <el-input v-model="form.licensePlateNumber" placeholder="请输入车牌号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
                <!-- <el-radio :label="2">未知</el-radio> -->
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isDisable">
              <el-switch
                v-model="form.isDisable"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="身份证正面" prop="frontOfIdCard">
              <!-- <el-upload
                class="avatar-uploader"
                action="/your-upload-api"
                :show-file-list="false"
                :on-success="(res) => form.frontOfIdCard = res.url"
              >
                <img v-if="form.frontOfIdCard" :src="form.frontOfIdCard" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload> -->
              <div class="upLoadPicBox" @click="modalPicTap(false, 'frontOfIdCard')">
                <div v-if="form.frontOfIdCard" class="pictrue">
                  <img :src="form.frontOfIdCard" />
                </div>
                <div v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
                <!-- <div class="from-tips">建议尺寸(180*180)</div> -->
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证反面" prop="backOfIdCard">
              <!-- <el-upload
                class="avatar-uploader"
                action="/your-upload-api"
                :show-file-list="false"
                :on-success="(res) => (form.backOfIdCard = res.url)"
              >
                <img v-if="form.backOfIdCard" :src="form.backOfIdCard" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload> -->
              <div class="upLoadPicBox" @click="modalPicTap(false, 'backOfIdCard')">
                <div v-if="form.backOfIdCard" class="pictrue">
                  <img :src="form.backOfIdCard" />
                </div>
                <div v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
                <!-- <div class="from-tips">建议尺寸(180*180)</div> -->
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="身份证有效期" prop="validityPeriodOfIdCard">
              <el-date-picker
                v-model="form.validityPeriodOfIdCard"
                type="date"
                placeholder="请选择日期"
                :disabled="form.isLongTerm === 1"
                style="width: 40%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
              <el-checkbox v-model="form.isLongTerm" :true-label="1" :false-label="0" style="margin-left: 20px">长期有效</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注说明" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer rider-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// getDelivery
import { listDelivery, delDelivery, addDelivery, updateDelivery } from '@/api/delivery';
import { listRoom } from '@/api/room';

import { parseTime } from '@/utils';

export default {
  name: 'Delivery',
  filters: {
    sexFilter(value) {
      const map = { 1: '男', 0: '女', 2: '未知' };
      return map[value] || '未知';
    },
  },
  data() {
    return {
      // 公共数据
      loading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      deliveryList: [],
      title: '',
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deliveryPersonnelName: null,
        deliveryPersonnelPhone: null,
        licensePlateNumber: null,
      },

      // 表单数据
      form: {
        id: null,
        deliveryPersonnelName: null,
        deliveryPersonnelPhone: null,
        password: null,
        sex: null,
        licensePlateNumber: null,
        idNumber: null,
        frontOfIdCard: null,
        backOfIdCard: null,
        validityPeriodOfIdCard: null,
        isLongTerm: 0,
        saleRoomId: null,
        isDisable: 1,
        remarks: null,
      },
      saleRoomList: [],
      // 验证规则
      rules: {
        deliveryPersonnelName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        deliveryPersonnelPhone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
        ],
        idNumber: [{ required: true, message: '身份证号不能为空', trigger: 'blur' }],
        frontOfIdCard: [{ required: true, message: '请上传身份证正面', trigger: 'change' }],
        backOfIdCard: [{ required: true, message: '请上传身份证反面', trigger: 'change' }],
        validityPeriodOfIdCard: [{ required: true, message: '请选择身份证有效期', trigger: 'change' }],
        saleRoomId: [{ required: true, message: '请选择归属门店', trigger: 'change' }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getOptions() {
      if(this.saleRoomList.length === 0) {
        listRoom({ pageNum: 1, pageSize: 100 }).then((response) => {
          this.saleRoomList = response.list;
        });
      }
    },
     // 点击商品图
    modalPicTap(multiple, type) {
      const _this = this;
      this.$modalUpload(
        function (img) {
          if (!img) return;
          _this.form[type] = img[0].sattDir;
        },
        multiple,
        'store',
      );
    },
    cancel() {
      this.reset();
      this.open = false;
    },
    /** 获取列表 */
    getList() {
      this.loading = true;
      listDelivery(this.queryParams).then((response) => {
        this.deliveryList = response.list;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        deliveryPersonnelName: null,
        deliveryPersonnelPhone: null,
        password: null,
        sex: null,
        licensePlateNumber: null,
        idNumber: null,
        frontOfIdCard: null,
        backOfIdCard: null,
        validityPeriodOfIdCard: null,
        isLongTerm: 0,
        saleRoomId: null,
        isDisable: 0,
        remarks: null,
      };
      this.resetForm('form');
    },

    /** 搜索按钮 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },

    /** 多选框选中 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加配送员';
      this.getOptions();
    },

    /** 修改按钮 */
    handleUpdate(row) {
      this.reset();
      //   const id = row.id || this.ids;
      //   getDelivery(id).then(response => {
      //     this.form = response.data;
      //     this.open = true;
      //     this.title = "修改配送员";
      //   });
      this.getOptions();

      this.open = true;
      this.title = '修改配送员';
      this.form = JSON.parse(JSON.stringify(row));
    },

    /** 提交表单 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            updateDelivery(this.form).then(() => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addDelivery(this.form).then(() => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('确认删除选中的数据？')
        .then(() => {
          return delDelivery(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },

    /** 导出按钮 */
    handleExport() {
      this.download(
        'platform/delivery/export',
        {
          ...this.queryParams,
        },
        `delivery_${new Date().getTime()}.xlsx`,
      );
    },

    // 时间格式化
    parseTime,
  },
};
</script>

<style scoped>
.mt14 {
  margin-top: 14px;
}
.padding-add {
  padding: 20px;
}
.rider-dialog >>> .el-dialog__body {
  background: #f8f9fb;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  padding: 30px 30px 10px 30px;
}
.rider-form .el-form-item {
  margin-bottom: 20px;
}
.rider-form .el-input,
.rider-form .el-select,
.rider-form .el-date-picker {
  width: 100%;
}
.rider-form .el-form-item__label {
  font-weight: 500;
  color: #333;
}
.rider-footer {
  text-align: center;
  padding: 20px 0 10px 0;
  border-top: 1px solid #ebeef5;
}
.rider-footer .el-button {
  min-width: 90px;
  border-radius: 4px;
  margin: 0 8px;
}
.avatar-uploader {
  display: inline-block;
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  background: #fff;
  position: relative;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}
</style>
